<<<<<<< HEAD
"""
【1.2 投资的收益和风险】：固定风险水平，优化收益
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linprog

plt.style.use(['science', 'muted', 'grid'])

# 目标函数(收益)
Q = np.array([0.05-0.00, 0.28-0.01, 0.21-0.02, 0.23-0.045, 0.35-0.065])
# 线性等式约束条件
A_eq = np.array([[1, 1+0.01, 1+0.02, 1+0.045, 1+0.065]])
b_eq = np.array([1])
# 线性不等式约束条件
alpha = 0  # 最大风险率alpha
delta_alpha = 0.001  # 步长
A = np.array([[0, 0.025, 0, 0, 0], [0, 0, 0.015, 0, 0],
              [0, 0, 0, 0.055, 0], [0, 0, 0, 0, 0.026]])
# 决策变量的下界与上界
lb = 0
ub = None
# 求解线性规划
plt.figure()
while (alpha < 0.05):
    b = np.array([alpha, alpha, alpha, alpha])
    res = linprog(-Q, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq,
                  bounds=((lb, ub), (lb, ub), (lb, ub), (lb, ub), (lb, ub)))
    # 输出
    print("风险度alpha: {}\n"
          "收益Q: {}\n"
          "x: {}".format(alpha, -res['fun'], res['x']))
    print("\n")
    alpha = alpha + delta_alpha
    plt.plot(alpha, -res['fun'], '*r')
plt.xlabel("alpha")
plt.ylabel("Q")
plt.savefig('alpha-Q.pdf')
=======
"""
【1.2 投资的收益和风险】：固定风险水平，优化收益
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linprog

plt.style.use(['science', 'muted', 'grid'])

# 目标函数(收益)
Q = np.array([0.05-0.00, 0.28-0.01, 0.21-0.02, 0.23-0.045, 0.35-0.065])
# 线性等式约束条件
A_eq = np.array([[1, 1+0.01, 1+0.02, 1+0.045, 1+0.065]])
b_eq = np.array([1])
# 线性不等式约束条件
alpha = 0  # 最大风险率alpha
delta_alpha = 0.001  # 步长
A = np.array([[0, 0.025, 0, 0, 0], [0, 0, 0.015, 0, 0],
              [0, 0, 0, 0.055, 0], [0, 0, 0, 0, 0.026]])
# 决策变量的下界与上界
lb = 0
ub = None
# 求解线性规划
plt.figure()
while (alpha < 0.05):
    b = np.array([alpha, alpha, alpha, alpha])
    res = linprog(-Q, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq,
                  bounds=((lb, ub), (lb, ub), (lb, ub), (lb, ub), (lb, ub)))
    # 输出
    print("风险度alpha: {}\n"
          "收益Q: {}\n"
          "x: {}".format(alpha, -res['fun'], res['x']))
    print("\n")
    alpha = alpha + delta_alpha
    plt.plot(alpha, -res['fun'], '*r')
plt.xlabel("alpha")
plt.ylabel("Q")
plt.savefig('alpha-Q.pdf')
>>>>>>> a66c8eec2c3bbe955d7da215f43ffffda9c7b6b5
plt.show()